package com.fsj.admin.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Package: com.stip.net.api.utils
 * @Description:
 * @Author: cgnet05
 * @CreatDate: 2019/02/27
 */
public class UploadImageUtil {
    protected static Logger logger = LoggerFactory.getLogger(UploadImageUtil.class);

    private String endpoint = "oss-cn-shanghai.aliyuncs.com";
    // accessKey
    private String accessKeyId = "LTAIlJFgNOUNL4DW";
    private String accessKeySecret = "tzRX9QAJJ6DGq1p3DOTW2FVdSvbZOQ";
    //空间
    private String bucketName = "payapay";
    //文件存储目录
    private String filedir = "imgs/";

    private OSSClient ossClient;

    public UploadImageUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 获得图片路径
     *
     * @param fileName
     * @return
     */
    public String getImgUrl(String fileName) {
        return "http://" + bucketName + "." + endpoint + "/" + filedir + fileName;
    }

    /**
     * 上传图片
     * @param request
     * @return
     * @throws IOException
     */
    public String uploadImage(HttpServletRequest request) throws IOException {
        Map<String, String> map = new HashMap<>();
        // 强制转换
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        // 获得file类型的input的name属性值
        Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        // 单个文件上传
        String name = fileNames.next();
        // 获得上传文件
        MultipartFile multipartFile = multipartHttpServletRequest.getFile(name);
        // 文件输入流
        InputStream inputStream = multipartFile.getInputStream();
        // 文件名称
        String fileName = multipartFile.getOriginalFilename();
        String newName = DateTimeUtils.formatDate(new Date(), "yyyyMMddHHmmss") + RandomUtils.generateNumberString(10);
        // 文件大小
//        long fileLength = multipartFile.getSize();
        // 文件返回ID
        String fileId;
        // 文件扩展名
        String fileExtName = "";
        if (fileName.contains(".")) {
            fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            // 图片文件类型过滤
            if (!"jpg".equals(fileExtName) && !"jpeg".equals(fileExtName) && !"png".equals(fileExtName) && !"gif".equals(fileExtName)) {
                logger.debug("上传失败,不支持图片类型. ==>> {}", fileExtName);
            }
        } else {
            logger.warn("Fail to upload file, because the format of filename is illegal. ==>> {}", fileName);
        }

        this.uploadFile2OSS(inputStream, newName + "." + fileExtName);
        return this.getImgUrl(newName + "." + fileExtName);
    }

    /**
     * 上传图片至OSS
     *
     * @param file 上传文件（文件全路径如：D:\\image\\cake.jpg）
     * @return String 返回的唯一MD5数字签名
     */
    public String uploadObject2OSS(File file) {
        String resultStr = null;
        try {
            //以输入流的形式上传文件
            InputStream is = new FileInputStream(file);
            //文件名
            String fileName = file.getName();
            //文件大小
            Long fileSize = file.length();
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            //上传的文件的长度
            metadata.setContentLength(is.available());
            //指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            //指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            //指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            //如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            //上传文件   (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, is, metadata);
            //解析结果
            resultStr = putResult.getETag();
        } catch (Exception e) {
//            e.printStackTrace();
            logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return resultStr;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileName));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            ossClient.shutdown();
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 流转字节数组
     *
     * @param inStream
     * @param fileLength
     * @return
     * @throws IOException
     */
    private byte[] getFileBuffer(InputStream inStream, long fileLength) throws IOException {
        return IOUtils.toByteArray(inStream);

    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            ossClient.shutdown();
            return url.toString();
        }
        ossClient.shutdown();
        return null;
    }

    /**
     * 创建存储空间
     *
     * @param ossClient  OSS连接
     * @param bucketName 存储空间
     * @return
     */
    public String createBucketName(OSSClient ossClient, String bucketName) {
        //存储空间
        final String bucketNames = bucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            //创建存储空间
            Bucket bucket = ossClient.createBucket(bucketName);
            logger.info("创建存储空间成功");
            return bucket.getName();
        }
        return bucketNames;
    }

    /**
     * 删除存储空间buckName
     *
     * @param ossClient  oss对象
     * @param bucketName 存储空间
     */
    public void deleteBucket(OSSClient ossClient, String bucketName) {
        ossClient.deleteBucket(bucketName);
        logger.info("删除" + bucketName + "Bucket成功");
    }

    /**
     * 创建模拟文件夹
     *
     * @param folder 模拟文件夹名如"qj_nanjing/"
     * @return 文件夹名
     */
    public String createFolder(String folder) {
        //文件夹名
        final String keySuffixWithSlash = folder;
        //判断文件夹是否存在，不存在则创建
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            //创建文件夹
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            logger.info("创建文件夹成功");
            //得到文件夹名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
            return fileDir;
        }
        return keySuffixWithSlash;
    }

    /**
     * 根据key删除OSS服务器上的文件
     *
     * @param folder 模拟文件夹名 如"qj_nanjing/"
     * @param key    Bucket下的文件的路径名+文件名 如："upload/cake.jpg"
     */
    public void deleteFile(String folder, String key) {
        ossClient.deleteObject(bucketName, folder + key);
        logger.info("删除" + bucketName + "下的文件" + folder + key + "成功");
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public String getContentType(String fileName) {
        //文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        //默认返回类型
        return "image/jpeg";
    }

    //测试
    public static void main(String[] args) {
        //初始化OSSClient
        File filess = new File("D:\\yzm.jpg");
        try {
            InputStream is = new FileInputStream(filess);
            String md5key = new UploadImageUtil().uploadFile2OSS(is, "yzm1.jpg");
            System.out.println(md5key);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
}
